from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer
from django.conf import settings
from itsdangerous import BadData
from rest_framework_jwt.settings import api_settings


def generate_save_user_token(openid):
    """
    对openid进行加密
    :param openid: 原始openid
    :return:   加密后的openid
    """
    # 1.创建序列化器对象
    serializer = TJSSerializer(settings.SECRET_KEY, expires_in=600)
    data = {'openid': openid}
    # 2.调用序列化器的dumps
    access_token_bytes = serializer.dumps(data)

    # 3.把加密后的openid返回
    return access_token_bytes.decode()


def check_save_user_token(openid_sign):
    """对加密的openid进行解密"""
    # 1.创建序列化器对象
    serializer = TJSSerializer(settings.SECRET_KEY, 600)
    try:
        # 2.调用loads方法对数据进行解密
        data = serializer.loads(openid_sign)  # 解密后还是一个字典
    except BadData:  # 如果解密失败,抛出BadData异常
        return None
    else:
        return data.get('openid')


def gennerate_token(user):
    # 手动生成jwt Token
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载生成载荷函数
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token函数
    # 获取user对象

    payload = jwt_payload_handler(user)  # 生成载荷
    token = jwt_encode_handler(payload)  # 根据载荷生成token
    return token